package com.ruoyi.tzai.service.impl;

import java.util.Date;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.tzai.domain.TaskStep;
import com.ruoyi.tzai.mapper.TaskStepMapper;
import com.ruoyi.tzai.service.ITaskStepService;

/**
 * 任务步骤Service业务层处理
 * 
 * @author tzai
 * @date 2025-11-12
 */
@Service
public class TaskStepServiceImpl implements ITaskStepService 
{
    private static final Logger log = LoggerFactory.getLogger(TaskStepServiceImpl.class);

    @Autowired
    private TaskStepMapper taskStepMapper;

    /**
     * 查询任务步骤
     * 
     * @param stepId 任务步骤主键
     * @return 任务步骤
     */
    @Override
    public TaskStep selectTaskStepByStepId(Long stepId)
    {
        return taskStepMapper.selectTaskStepByStepId(stepId);
    }

    /**
     * 查询任务步骤列表
     * 
     * @param taskStep 任务步骤
     * @return 任务步骤
     */
    @Override
    public List<TaskStep> selectTaskStepList(TaskStep taskStep)
    {
        return taskStepMapper.selectTaskStepList(taskStep);
    }

    /**
     * 根据任务ID查询所有步骤
     * 
     * @param taskId 任务ID
     * @return 步骤列表
     */
    @Override
    public List<TaskStep> selectStepsByTaskId(Long taskId)
    {
        return taskStepMapper.selectStepsByTaskId(taskId);
    }

    /**
     * 根据任务ID和步骤名称查询步骤
     * 
     * @param taskId 任务ID
     * @param stepName 步骤名称
     * @return 任务步骤
     */
    @Override
    public TaskStep selectStepByTaskIdAndName(Long taskId, String stepName)
    {
        return taskStepMapper.selectStepByTaskIdAndName(taskId, stepName);
    }

    /**
     * 新增任务步骤
     * 
     * @param taskStep 任务步骤
     * @return 结果
     */
    @Override
    public int insertTaskStep(TaskStep taskStep)
    {
        taskStep.setCreateTime(DateUtils.getNowDate());
        return taskStepMapper.insertTaskStep(taskStep);
    }

    /**
     * 修改任务步骤
     * 
     * @param taskStep 任务步骤
     * @return 结果
     */
    @Override
    public int updateTaskStep(TaskStep taskStep)
    {
        taskStep.setUpdateTime(DateUtils.getNowDate());
        return taskStepMapper.updateTaskStep(taskStep);
    }

    /**
     * 批量删除任务步骤
     * 
     * @param stepIds 需要删除的任务步骤主键
     * @return 结果
     */
    @Override
    public int deleteTaskStepByStepIds(Long[] stepIds)
    {
        return taskStepMapper.deleteTaskStepByStepIds(stepIds);
    }

    /**
     * 删除任务步骤信息
     * 
     * @param stepId 任务步骤主键
     * @return 结果
     */
    @Override
    public int deleteTaskStepByStepId(Long stepId)
    {
        return taskStepMapper.deleteTaskStepByStepId(stepId);
    }

    /**
     * 为任务初始化所有步骤
     * 
     * @param taskId 任务ID
     */
    @Override
    @Transactional
    public void initializeSteps(Long taskId)
    {
        log.info("初始化任务步骤: taskId={}", taskId);
        
        // 步骤1：文本清理
        TaskStep step1 = new TaskStep();
        step1.setTaskId(taskId);
        step1.setStepName("text_clean");
        step1.setStepOrder(1);
        step1.setStatus("pending");
        step1.setProgress(0);
        step1.setCreateTime(new Date());
        taskStepMapper.insertTaskStep(step1);
        
        // 步骤2：AI处理
        TaskStep step2 = new TaskStep();
        step2.setTaskId(taskId);
        step2.setStepName("ai_process");
        step2.setStepOrder(2);
        step2.setStatus("pending");
        step2.setProgress(0);
        step2.setCreateTime(new Date());
        taskStepMapper.insertTaskStep(step2);
        
        // 步骤3：TTS生成（中文）
        TaskStep step3 = new TaskStep();
        step3.setTaskId(taskId);
        step3.setStepName("tts_generate_cn");
        step3.setStepOrder(3);
        step3.setStatus("pending");
        step3.setProgress(0);
        step3.setCreateTime(new Date());
        taskStepMapper.insertTaskStep(step3);
        
        // 步骤4：TTS生成（英文）
        TaskStep step4 = new TaskStep();
        step4.setTaskId(taskId);
        step4.setStepName("tts_generate_en");
        step4.setStepOrder(4);
        step4.setStatus("pending");
        step4.setProgress(0);
        step4.setCreateTime(new Date());
        taskStepMapper.insertTaskStep(step4);
        
        log.info("任务步骤初始化完成: taskId={}, stepCount=4", taskId);
    }

    /**
     * 开始步骤
     * 
     * @param stepId 步骤ID
     */
    @Override
    @Transactional
    public void startStep(Long stepId)
    {
        TaskStep step = new TaskStep();
        step.setStepId(stepId);
        step.setStatus("running");
        step.setStartedAt(new Date());
        step.setProgress(0);
        step.setUpdateTime(new Date());
        taskStepMapper.updateTaskStep(step);
        
        log.debug("步骤开始: stepId={}", stepId);
    }

    /**
     * 完成步骤
     * 
     * @param stepId 步骤ID
     * @param outputData 输出数据
     */
    @Override
    @Transactional
    public void completeStep(Long stepId, String outputData)
    {
        TaskStep step = taskStepMapper.selectTaskStepByStepId(stepId);
        if (step == null) {
            log.error("步骤不存在: stepId={}", stepId);
            return;
        }
        
        Date now = new Date();
        int duration = 0;
        if (step.getStartedAt() != null) {
            duration = (int) ((now.getTime() - step.getStartedAt().getTime()) / 1000);
        }
        
        TaskStep updateStep = new TaskStep();
        updateStep.setStepId(stepId);
        updateStep.setStatus("completed");
        updateStep.setCompletedAt(now);
        updateStep.setDuration(duration);
        updateStep.setProgress(100);
        if (outputData != null) {
            updateStep.setOutputData(outputData);
        }
        updateStep.setUpdateTime(now);
        taskStepMapper.updateTaskStep(updateStep);
        
        log.info("步骤完成: stepId={}, duration={}s", stepId, duration);
    }

    /**
     * 步骤失败
     * 
     * @param stepId 步骤ID
     * @param error 错误信息
     */
    @Override
    @Transactional
    public void failStep(Long stepId, String error)
    {
        TaskStep step = new TaskStep();
        step.setStepId(stepId);
        step.setStatus("failed");
        step.setErrorMessage(error);
        step.setCompletedAt(new Date());
        step.setUpdateTime(new Date());
        taskStepMapper.updateTaskStep(step);
        
        log.error("步骤失败: stepId={}, error={}", stepId, error);
    }

    /**
     * 更新步骤进度
     * 
     * @param stepId 步骤ID
     * @param progress 进度(0-100)
     */
    @Override
    @Transactional
    public void updateStepProgress(Long stepId, int progress)
    {
        TaskStep step = new TaskStep();
        step.setStepId(stepId);
        step.setProgress(progress);
        step.setUpdateTime(new Date());
        taskStepMapper.updateTaskStep(step);
        
        log.debug("更新步骤进度: stepId={}, progress={}%", stepId, progress);
    }

    /**
     * 保存步骤断点数据
     * 
     * @param stepId 步骤ID
     * @param jsonPath JSON路径
     * @param value 值
     */
    @Override
    @Transactional
    public void saveStepCheckpoint(Long stepId, String jsonPath, String value)
    {
        try {
            taskStepMapper.updateStepOutputDataField(stepId, jsonPath, value);
            log.debug("保存断点: stepId={}, path={}", stepId, jsonPath);
        } catch (Exception e) {
            log.error("保存断点失败: stepId={}, path={}", stepId, jsonPath, e);
        }
    }

    /**
     * 加载步骤断点数据
     * 
     * @param stepId 步骤ID
     * @return 断点数据JSON
     */
    @Override
    public String loadStepCheckpoint(Long stepId)
    {
        TaskStep step = taskStepMapper.selectTaskStepByStepId(stepId);
        if (step == null) {
            return null;
        }
        return step.getOutputData();
    }

    /**
     * 删除指定时间之前的步骤
     * 
     * @param days 天数
     * @return 删除数量
     */
    @Override
    @Transactional
    public int deleteStepsBefore(int days)
    {
        Date beforeDate = DateUtils.addDays(new Date(), -days);
        return taskStepMapper.deleteStepsBefore(beforeDate);
    }

    /**
     * 根据任务ID删除所有步骤
     * 
     * @param taskId 任务ID
     * @return 删除数量
     */
    @Override
    @Transactional
    public int deleteStepsByTaskId(Long taskId)
    {
        return taskStepMapper.deleteStepsByTaskId(taskId);
    }
}

